package com.hzmg.handler;

import akka.actor.typed.Behavior;
import akka.actor.typed.javadsl.Behaviors;
import com.hzmg.filter.GatewayFilter;
import com.hzmg.filter.GatewayFilterChain;
import com.hzmg.route.RouteDefinition;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;

import java.util.List;

public class AkkaFilterHandler {

    private final List<GatewayFilter> gatewayFilters;


    public AkkaFilterHandler(List<GatewayFilter> gatewayFilters) {
        this.gatewayFilters = gatewayFilters;
    }

    public Behavior<Void> handle(RouteDefinition routeDefinition) {
        List<GatewayFilter> filters = gatewayFilters;

        AnnotationAwareOrderComparator.sort(filters);

        return new DefaultGatewayFilterChain(filters).filter(routeDefinition);
    }

    private static class DefaultGatewayFilterChain implements GatewayFilterChain {

        private int index;

        private final List<GatewayFilter> gatewayFilters;

        private DefaultGatewayFilterChain(List<GatewayFilter> gatewayFilters) {
            this.gatewayFilters = gatewayFilters;
        }

        @Override
        public Behavior<Void> filter(RouteDefinition routeDefinition) {
            if (this.index < gatewayFilters.size()) {
                GatewayFilter gatewayFilter = gatewayFilters.get(index++);
                return gatewayFilter.filter(routeDefinition, this);
            } else {
                return Behaviors.empty();
            }
        }
    }
}
